/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.weike;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.custom.SoundView;
import com.tstudy.laoshibang.custom.SoundView.OnVolumeChangedListener;
import com.tstudy.laoshibang.event.WeikeLoveEvent;
import com.tstudy.laoshibang.event.WeikePlayEvent;
import com.tstudy.laoshibang.login.LoginActivity;
import com.tstudy.laoshibang.mode.Weike;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.WeikeDetailResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
@SuppressWarnings("deprecation")
@EFragment(R.layout.weike_detail_player)
public class WeikeDetailPlayerFragment extends BaseFragment implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback{
	final static String TAG = "weike_detail_player";
	public WeikeDetailPlayerFragment() {
		super();
	}
	
	 private int mVideoWidth;
	 private int mVideoHeight;
	    private MediaPlayer mMediaPlayer;
	    private boolean mIsPrepared;
	    private int mDuration;
	    private SurfaceHolder holder;
	    private String path;
	    private Bundle extras;
	    private boolean mIsVideoSizeKnown = false;
	    private boolean mIsVideoReadyToBePlayed = false;
	    
	    private View controlView = null;
		private PopupWindow controlerPop = null;
		private TextView durationTextView = null;
		private int mCurrentBufferPercentage;
		private TextView playedTextView = null;
		private SeekBar seekBar = null;  
		private int mProgress;
		private int mScale = 30*1000;
		private int mPlayedTime;
		private ImageButton fullScreen = null;
		private ImageButton backward = null;
		private ImageButton start = null;
		private ImageButton forward = null;
		private ImageButton sound = null;
		private GestureDetector mGestureDetector = null;
		private AudioManager mAudioManager = null;  
		
		private SoundView mSoundView = null;
//		private PopupWindow mSoundWindow = null;
		
		private View extralView = null;
		private static int mControlHeight = BaseApplication.getResDimen(R.dimen.video_control_height);
		private static int mTitleHeight = BaseApplication.getResDimen(R.dimen.common_title_height);
		private static int nHeaderHeight = (int)(BaseApplication.mScreenWidth*CONSTANT.weike_header_scale);
		private int maxVolume = 0;
		private int currentVolume = 0;  
		private final static int TIME = 6868;  
		private boolean isControllerShow = true;
		private boolean isPaused = false;
		private boolean isFullScreen = false;
		private boolean isSilent = false;
		private boolean isSoundShow = false;
		private boolean isOnline = false; 
		private boolean isChangedVideo = false;
		private boolean mStartWhenPrepared;
	    private int   mSeekWhenPrepared;
	
	@ViewById(R.id.weike_detail_player_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.weike_detail_player_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.weike_detail_player_video_view)
	SurfaceView mVideoView;
	
	@ViewById(R.id.weike_detail_player_layout)
	RelativeLayout mVideoLayout;
	
	@ViewById(R.id.weike_detail_player_weike_title)
	TextView mWeikeTitle;
	
	@ViewById(R.id.weike_detail_player_view_count)
	TextView mViewCount;
	
	@ViewById(R.id.weike_detail_player_love_count)
	TextView mLoveCount;
	
	@ViewById(R.id.weike_detail_player_love_icon)
	ImageView mLoveIcon;
	
	@ViewById(R.id.weike_detail_player_video_icon)
	ImageView mVideoIcon;
	
	@ViewById(R.id.weike_detail_player_content)
	WebView mContent;
	
	boolean mIsFirstLoad = true;
	LayoutInflater mInflater;
	
	public static final int BANNER_DURATION = 3000;
	int mCurrentPosition = 0;
	List<View> mViewList = new ArrayList<View>();
	int mWeikeId;
	int mPosition;
	String mGroupId;
	Weike mWeike;
	int heightPosition = nHeaderHeight + BaseApplication.mStatusBarHeight + mTitleHeight -mControlHeight;
	public static void add(int containerViewId,int weikeId,int poistion) {
		add(containerViewId, weikeId, poistion,null);
	}
	public static void add(int containerViewId,int weikeId,int poistion,String groupId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putInt(CONSTANT.ARGS.WEIKE_ID, weikeId);
		args.putInt(CONSTANT.ARGS.POSITION, poistion);
		args.putString(CONSTANT.ARGS.GROUP_ID, groupId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,WeikeDetailPlayerFragment_.class.getName(),args);
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			mProgressLayout.setVisibility(View.VISIBLE);
			mVideoLayout.getLayoutParams().height = nHeaderHeight;
			initController();
//	    	initSoundView();
	    	mVideoView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(!isControllerShow){
						showController();
						hideControllerDelay();
					}else {
						cancelDelayHide();
						hideController();
					}
				}
			});
	    	mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getWeikeDetail();
					if(controlerPop != null && mVideoView.isShown()){
						controlerPop.showAsDropDown(mVideoView, 0, -mControlHeight);
					}
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			
		}
	}
    
    public void initController(){
    	 controlView = mInflater.inflate(R.layout.controler, null);
         controlerPop = new PopupWindow(controlView);
         fullScreen = (ImageButton) controlView.findViewById(R.id.fullscreen);
         backward = (ImageButton) controlView.findViewById(R.id.backward);
         start = (ImageButton) controlView.findViewById(R.id.start);
         forward = (ImageButton) controlView.findViewById(R.id.forward);
         sound = (ImageButton) controlView.findViewById(R.id.sound);
         durationTextView = (TextView) controlView.findViewById(R.id.duration);
         playedTextView = (TextView) controlView.findViewById(R.id.has_played);
         fullScreen.setOnClickListener(new OnClickListener(){
 			@Override
 			public void onClick(View arg0) {
 				if (!TextUtils.isEmpty(path)) {
// 					MediaPlayerActivity.show(getActivity(), mPlayedTime, path);
 					MediaPlayerFullScreen.show(WeikeDetailPlayerFragment.this.getActivity(), getCurrentPosition(), path);
				}
// 				if(isFullScreen){
// 					setVideoScale(SCREEN_DEFAULT);
// 				}else{
// 					setVideoScale(SCREEN_FULL);
// 				}
// 				isFullScreen = !isFullScreen;
// 				Log.d(TAG, "onDoubleTap");
// 				
// 				if(isControllerShow){
// 					showController();
// 				}
//// 				Intent intent = new Intent();
//// 				intent.setClass(VideoPlayerActivity.this, VideoChooseActivity.class);
//// 				VideoPlayerActivity.this.startActivityForResult(intent, 0);
//// 				cancelDelayHide();
 			}
         	
         });
         backward.setOnClickListener(new OnClickListener(){
 			@Override
 			public void onClick(View v) {
 				seekTo(Math.max(0,getCurrentPosition() - mScale));
 			}
         });
         forward.setOnClickListener(new OnClickListener(){
 			@Override
 			public void onClick(View v) {
 				seekTo(Math.min(mDuration,getCurrentPosition() + mScale));
 			}
         	
         });
         start.setOnClickListener(new OnClickListener(){
 			@Override
 			public void onClick(View v) {
 				cancelDelayHide();
 				if(isPaused){
 					start();
 					start.setImageResource(R.drawable.player_pause);
 					hideControllerDelay();
 				}else{
 					pause();
 					start.setImageResource(R.drawable.player_paly);
 				}
 				isPaused = !isPaused;
 			}
         	
         });
         
         seekBar = (SeekBar) controlView.findViewById(R.id.seekbar);
         seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
 				@Override
 				public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
 					if(fromUser){
 						if(!isOnline){
 							seekTo(progress);
 						}
 					}
 				}
 	
 				@Override
 				public void onStartTrackingTouch(SeekBar arg0) {
 					mHandler.removeMessages(HIDE_CONTROLER);
 				}
 	
 				@Override
 				public void onStopTrackingTouch(SeekBar seekBar) {
 					// TODO Auto-generated method stub
 					mHandler.sendEmptyMessageDelayed(HIDE_CONTROLER, TIME);
 				}
         	});
    }
    
    public void initSoundView(){
    	mSoundView = new SoundView(this.getActivity());
        mSoundView.setOnVolumeChangeListener(new OnVolumeChangedListener(){

			@Override
			public void setYourVolume(int index) {
				 
				cancelDelayHide();
				updateVolume(index);
				hideControllerDelay();
			}
        });
        mAudioManager = (AudioManager) BaseApplication.mContext.getSystemService(Context.AUDIO_SERVICE);
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//        mSoundWindow = new PopupWindow(mSoundView);
//        sound.setOnClickListener(new OnClickListener(){
//     		@Override
//     		public void onClick(View v) {
//     			// TODO Auto-generated method stub
//     			cancelDelayHide();
//     			if(isSoundShow){
//     				mSoundWindow.dismiss();
//     			}else{
//     				if(mSoundWindow.isShowing()){
//     					mSoundWindow.update(15,0,SoundView.MY_WIDTH,SoundView.MY_HEIGHT);
//     				}else{
//     					mSoundWindow.showAtLocation(mVideoView, Gravity.RIGHT|Gravity.CENTER_VERTICAL, 15, 0);
//     					mSoundWindow.update(15,0,SoundView.MY_WIDTH,SoundView.MY_HEIGHT);
//     				}
//     			}
//     			isSoundShow = !isSoundShow;
//     			hideControllerDelay();
//     		}   
//            });
//             sound.setOnLongClickListener(new OnLongClickListener(){
//     			@Override
//     			public boolean onLongClick(View arg0) {
//     				// TODO Auto-generated method stub
//     				if(isSilent){
//     					sound.setImageResource(R.drawable.soundenable);
//     				}else{
//     					sound.setImageResource(R.drawable.sounddisable);
//     				}
//     				isSilent = !isSilent;
//     				updateVolume(currentVolume);
//     				cancelDelayHide();
//     				hideControllerDelay();
//     				return true;
//     			}
//             	
//             });
    }
    
	
	public void setView(){
		if (mWeike != null) {
			mWeikeTitle.setText(mWeike.title);
			mLoveCount.setText(mWeike.praiseNum + "");
			mLoveIcon.setSelected(mWeike.isPraise==1);
			String viewCountStr = BaseApplication.getResString(R.string.weike_detail_view_count);
			mViewCount.setText(String.format(viewCountStr, mWeike.playNum));
			mContent.loadData(mWeike.detail, "text/html; charset=UTF-8",null);
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if (mWeike.videos != null) {
						path = mWeike.videos.get(0).videoIdxName;
						holder = mVideoView.getHolder();
				        holder.addCallback(WeikeDetailPlayerFragment.this);
				        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
				        playAction(mWeike.videos.get(0).coseIdxId,CONSTANT.PLAY_TYPE_WEIKE);
				        playVideo();
					}
				}
			},1);
			
		}
	}
	
//	@Override
//	public boolean onTouchEvent(MotionEvent event) {
//		boolean result = mGestureDetector.onTouchEvent(event);
//		
//		if(!result){
//			if(event.getAction()==MotionEvent.ACTION_UP){
//				
//				/*if(!isControllerShow){
//					showController();
//					hideControllerDelay();
//				}else {
//					cancelDelayHide();
//					hideController();
//				}*/
//			}
//			result = super.onTouchEvent(event);
//		}
//		
//		return result;
//	}
    private final static int PROGRESS_CHANGED = 0;
    private final static int HIDE_CONTROLER = 1;
    
    private void updateVolume(int index){
    	if(mAudioManager!=null){
    		if(isSilent){
    			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
    		}else{
    			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
    		}
    		currentVolume = index;
    		sound.setAlpha(findAlphaFromSound());
    	}
    }
    private int findAlphaFromSound(){
    	if(mAudioManager!=null){
    		//int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    		int alpha = currentVolume * (0xCC-0x55) / maxVolume + 0x55;
    		return alpha;
    	}else{
    		return 0xCC;
    	}
    }
    Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case PROGRESS_CHANGED:
					int i = getCurrentPosition();
					seekBar.setProgress(i);
					if(isOnline){
						int j = getBufferPercentage();
						seekBar.setSecondaryProgress(j * seekBar.getMax() / 100);
					}else{
						seekBar.setSecondaryProgress(0);
					}
					i/=1000;
					int minute = i/60;
					int hour = minute/60;
					int second = i%60;
					minute %= 60;
					playedTextView.setText(String.format("%02d:%02d:%02d", hour,minute,second));
					
					sendEmptyMessageDelayed(PROGRESS_CHANGED, 100);
					break;
				case HIDE_CONTROLER:
					hideController();
					break;
			}
			super.handleMessage(msg);
		}	
    };
    
    public int getBufferPercentage() {
        if (mMediaPlayer != null) {
            return mCurrentBufferPercentage;
        }
        return 0;
    }
    
    public int getCurrentPosition() {
        if (mMediaPlayer != null && mIsPrepared) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }
    
    private void hideController(){
		if(controlerPop.isShowing()){
			controlerPop.update(0,-mControlHeight,0,-mControlHeight);
			controlerPop.dismiss();
			isControllerShow = false;
		}
	}
	
	private void hideControllerDelay(){
		mHandler.sendEmptyMessageDelayed(HIDE_CONTROLER, TIME);
	}
	
	private void showController(){
		controlerPop.showAsDropDown(mVideoView, 0, -mControlHeight);
		controlerPop.update(0,heightPosition,BaseApplication.mScreenWidth,mControlHeight);
		isControllerShow = true;
	}
	
	private void cancelDelayHide(){
		mHandler.removeMessages(HIDE_CONTROLER);
	}
	
	private void playVideo() {
        doCleanUp();
        try {
            LogUtil.d("------path==" + path);
            mCurrentBufferPercentage = 0;
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setDisplay(holder);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnBufferingUpdateListener(this);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnVideoSizeChangedListener(this);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } catch (Exception e) {
            LogUtil.d("error: " + e.getMessage(), e);
        }
    }

    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        LogUtil.d("onBufferingUpdate percent:" + percent);
        mCurrentBufferPercentage = percent;
    }

    public void onCompletion(MediaPlayer arg0) {
        LogUtil.d("onCompletion called");
    }

    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        LogUtil.d("onVideoSizeChanged called");
        if (width == 0 || height == 0) {
            LogUtil.d("invalid video width(" + width + ") or height(" + height + ")");
            return;
        }
        mIsVideoSizeKnown = true;
        mVideoWidth = width;
        mVideoHeight = height;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
//            startVideoPlayback();
        }
    }

    public void onPrepared(MediaPlayer mediaplayer) {
        LogUtil.d("onPrepared called" + this);
        mIsVideoReadyToBePlayed = true;
        mIsPrepared = true;
        isFullScreen = false; 
		if(isControllerShow){
			showController();  
		}
		int i = getDuration();
		LogUtil.d("onCompletion" +i);
		seekBar.setMax(i);
		i/=1000;
		int minute = i/60;
		int hour = minute/60;
		int second = i%60;
		minute %= 60;
		durationTextView.setText(String.format("%02d:%02d:%02d", hour,minute,second));
		/*controler.showAtLocation(vv, Gravity.BOTTOM, 0, 0);
		controler.update(screenWidth, controlHeight);
		myHandler.sendEmptyMessageDelayed(HIDE_CONTROLER, TIME);*/
		start();  
		seekTo(mPlayedTime);
		start.setImageResource(R.drawable.player_pause);
		hideControllerDelay();
		mHandler.sendEmptyMessage(PROGRESS_CHANGED);
		hideProgressBar(mProgressLayout);
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }
    
    public int getDuration() {
        if (mMediaPlayer != null && mIsPrepared) {
            if (mDuration > 0) {
                return mDuration;
            }
            mDuration = mMediaPlayer.getDuration();
            return mDuration;
        }
        mDuration = -1;
        return mDuration;
    }
    
    public void start() {
        if (mMediaPlayer != null && mIsPrepared) {
                mMediaPlayer.start();
                mStartWhenPrepared = false;
        } else {
            mStartWhenPrepared = true;
        }
    }

    public void pause() {
        if (mMediaPlayer != null && mIsPrepared) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
            }
        }
        mStartWhenPrepared = false;
    }
    
    public void seekTo(int msec) {
        if (mMediaPlayer != null && mIsPrepared) {
            mMediaPlayer.seekTo(msec);
        } else {
            mSeekWhenPrepared = msec;
        }
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null && mIsPrepared) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }
    public void stopPlayback() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }


    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
        LogUtil.d("surfaceChanged called" + this);

    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
    	stopPlayback();
        LogUtil.d("surfaceDestroyed called" + this);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        LogUtil.d("surfaceCreated called" + this);
        showProgressBar(mProgressLayout);
        playVideo();

    }

    @Override
	public void onPause() {
		mPlayedTime = getCurrentPosition();
		pause();
		start.setImageResource(R.drawable.player_paly);
		super.onPause();   
	}

	@Override
	public void onResume() {
		if(!isChangedVideo || !mIsPost){
			start();  
		}else{
			isChangedVideo = false;
		}
		if(isPlaying()){
			start.setImageResource(R.drawable.player_pause);
			hideControllerDelay();
		}
//		if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
//			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//		}
		
		super.onResume();
	}
	boolean mIsPost = false;
	public void onEventMainThread(Integer position) {
		mPlayedTime = position.intValue();
		mIsPost = true;
	}

	
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	EventBus.getDefault().unregister(this);
    	if(controlerPop.isShowing()){
			controlerPop.dismiss();
		}
//		if(mSoundWindow.isShowing()){
//			mSoundWindow.dismiss();
//		}
		mHandler.removeMessages(PROGRESS_CHANGED);
		mHandler.removeMessages(HIDE_CONTROLER);
		if(isPlaying()){
			stopPlayback();
		}
    }

    private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsPrepared = false;
        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;
    }

    private void startVideoPlayback() {
    	LogUtil.d("--startVideoPlayback execute ==" );
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
    }
	
//	public void play(final VideoView videoView,final ImageView videoIcon,final ImageView img,String path){
////		videoIcon.setVisibility(View.GONE);
////		img.setVisibility(View.GONE);
//		videoView.setVisibility(View.VISIBLE);
//		videoView.setVideoPath(path);
//		videoView.setMediaController(new MediaController(getActivity()));
//		videoView.requestFocus();
//		videoView.start();
////		videoView.setOnPreparedListener(new OnPreparedListener() {
////			public void onPrepared(MediaPlayer mediaPlayer) {
////				// close the progress bar and play the video
//////				progressDialog.dismiss();
////				//if we have a position on savedInstanceState, the video playback should start from here
//////				mVideoView.seekTo(position);
//////				if (position == 0) {
////					videoView.start();
//////				} else {
////					//if we come from a resumed activity, video playback will be paused
//////					mVideoView.pause();
//////				}
////			}
////		});
////		videoView.setOnCompletionListener(new OnCompletionListener() {
////			@Override
////			public void onCompletion(MediaPlayer mp) {
////				videoIcon.setVisibility(View.VISIBLE);
////				img.setVisibility(View.VISIBLE);
////				videoView.setVisibility(View.GONE);
////			}
////		});
//	}
	
	@Click({R.id.weike_detail_player_back,R.id.weike_detail_player_share,R.id.weike_detail_player_love_icon})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.weike_detail_player_back:
			backAction(mFragmentId);
			break;
		case R.id.weike_detail_player_share:
//			showShareDialog();
			if (mWeike != null) {
				share(mWeike);
			}
			break;
		case R.id.weike_detail_player_love_icon:
			if (BaseApplication.checkLogin()) {
				if (mWeike != null) {
					mWeike.isPraise = mWeike.isPraise==1?0:1;
					view.setSelected(mWeike.isPraise==1);
					CommonUtil.loveAnimator(view);
					mWeike.praiseNum = mWeike.isPraise==0?mWeike.praiseNum-1:mWeike.praiseNum +1;
					mLoveCount.setText(mWeike.praiseNum+"");
					loveAction(mWeike.coseId,CONSTANT.ASSO_TYPE_WEIKE,mWeike.isPraise==0?CONSTANT.UNLOVE_ACTION:CONSTANT.LOVE_ACTION);
				}
			}else{
				LoginActivity.show();
			}
		default:
			break;
		}
	}
	Dialog mShareDialog;
	LinearLayout mDialogView;
	public void share(Weike weike){
		String mDefaultShareStr = BaseApplication.getResString(R.string.community_list_title);
		String mShareImg = null;
		if (weike.videos != null && weike.videos.size() > 0) {
			mShareImg = weike.videos.get(0).imgIdxName;
		}
		if(mShareDialog == null){
			mDialogView = (LinearLayout) mInflater.inflate(R.layout.share_pop, null);
			mShareDialog = buildAlertDialog(mDialogView,CommonUtil.dip2px(20));
		}
		if (mShareDialog.isShowing()) {
			return;
		}
		final String title = TextUtils.isEmpty(weike.title)?mDefaultShareStr:weike.title;
		final String content = TextUtils.isEmpty(weike.summary)?mDefaultShareStr:weike.summary;
		CommonUtil.showShareDialog(CONSTANT.ASSO_TYPE_WEIKE, mDialogView,mShareDialog, mInflater, mShareImg, title, content,weike.shareUrl);
	}
	
	@SuppressLint("InflateParams")
	public void showShareDialog(){
		LinearLayout dialogView = (LinearLayout) mInflater.inflate(R.layout.share_pop, null);
		if(mShareDialog != null && mShareDialog.isShowing()){
			return;
		}
		mShareDialog = buildAlertDialog(dialogView,CommonUtil.dip2px(20));
		TextView qqIcon = (TextView) dialogView.findViewById(R.id.share_pop_qq);
		TextView qzoneIcon = (TextView) dialogView.findViewById(R.id.share_pop_qzone);
		TextView wechatIcon = (TextView) dialogView.findViewById(R.id.share_pop_wechat);
		TextView wechatTimeLineIcon = (TextView) dialogView.findViewById(R.id.share_pop_wechat_timeline);
		TextView weiboIcon = (TextView) dialogView.findViewById(R.id.share_pop_weibo);
		qqIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mShareDialog.dismiss();
				((BaseActivity)getActivity()).logout();
			}
		});
		qzoneIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mShareDialog.dismiss();
			}
		});
		wechatIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mShareDialog.dismiss();
			}
		});
		wechatTimeLineIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mShareDialog.dismiss();
			}
		});
		weiboIcon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mShareDialog.dismiss();
			}
		});
		mShareDialog.show();
	}
	
	/**
	 * 微课点赞
	 * @param weikeId
	 * @param type
	 * @param isPraise
	 */
	private void loveAction(int weikeId,int type,final int isPraise){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
//					int count = mWeike.isPraise==1?mWeike.praiseNum-1:mWeike.praiseNum +1;
//					mLoveCount.setText(count+"");
					if (CommonUtil.responseSuccess(response)) {
						if (mPosition >= 0) {
							WeikeLoveEvent event = new WeikeLoveEvent();
							event.isPrised = isPraise;
							event.position = mPosition;
							EventBus.getDefault().post(event);
						}
					}
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().loveAction(BaseApplication.mUserNo, type, weikeId, isPraise,mGroupId, response);
	}
	
	private void playAction(int assoId,int type){
		ResponseHandlerInterface response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mPosition >= 0) {
						WeikePlayEvent event = new WeikePlayEvent();
						event.position = mPosition;
						EventBus.getDefault().post(event);
					}
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().playAction(BaseApplication.mUserNo, type, assoId,mGroupId,response);
	}
	
	private void getWeikeDetail(){
		if (mIsLoading) {
			return;
		}
		mIsLoading = true;
		ResponseHandlerInterface response = new BaseListJsonHandler<WeikeDetailResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, WeikeDetailResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					mWeike = response.getData();
					setView();
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					WeikeDetailResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected WeikeDetailResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,WeikeDetailResponse.class);
			}
		};
		HttpManager.getInstance().getWeikeDetail(BaseApplication.mUserNo, mWeikeId,mGroupId,response);
	}

	public void afterLoading(){
		mIsLoading = false;
//		hideProgressBar(mProgressLayout);
	}
	@Override
	public void clear() {
		// TODO Auto-generated method stub
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mWeikeId = args.getInt(CONSTANT.ARGS.WEIKE_ID);
			mPosition = args.getInt(CONSTANT.ARGS.POSITION);
			mGroupId = args.getString(CONSTANT.ARGS.GROUP_ID);
		}
	}

}
